package com.demo.function.spring.listener.service;

import com.demo.mapper.UserMapper;
import com.demo.model.entity.User;
import com.demo.model.dto.OrderHeader;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.PayloadApplicationEvent;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 测试 ShardingJDBC 分库
 * @author K
 */
@Slf4j
@Service
public class ApplicationEventListenerService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private ApplicationEventPublisher applicationEventPublisher;

    @Transactional(rollbackFor = Exception.class)
    public void insertAfterPublisherForUser(long userId) {
        User user = new User();
        user.setUserId(userId);
        userMapper.insert(user);
        log.info("user 保存成功");
        applicationEventPublisher.publishEvent(new PayloadApplicationEvent<>("insert", user));
    }

    /**
     * 验证多个事件监听，其中一个事件异常，是否影响其他事件
     * @param orderId 订单id
     */
    @Transactional(rollbackFor = Exception.class)
    public void insertAfterPublisherForOrderHeader(Long orderId) {
        OrderHeader orderHeader = new OrderHeader();
        orderHeader.setOrderId(orderId);
        log.info("orderHeader 保存成功");
        applicationEventPublisher.publishEvent(new PayloadApplicationEvent<>("insert", orderHeader));
    }

    public void orderlyEventListener() {
        for (int i = 0; i < 5; i++) {
            applicationEventPublisher.publishEvent(new PayloadApplicationEvent<>("insert", i));
        }
        log.info("出发事件完毕");
    }
}
